import React, { useRef, useEffect, useMemo } from "react";
import { Form as AntdForm, Input } from "antd";
import { useDrag } from "react-dnd";
import { useMaterialDrop } from "@editor/hooks/useMaterialDrop";

import { CommonComponentProps } from "../Page/dev";

export default function Form({ id, name, children, onFinish }: CommonComponentProps) {
    const divRef = useRef<HTMLDivElement | null>(null);
    const [_, drag] = useDrag({
        type: 'Form',
        item: {
            type: name,
            dragType: 'move',
            id
        }
    })
    const { canDrop, drop } = useMaterialDrop(['FormItem'], id)
    useEffect(() => {
        drag(divRef);
        drop(divRef);
    }, [])

    const [form] = AntdForm.useForm()
    const formItems = useMemo(() => {
        return React.Children.map(children, (item: any) => {
            return {
                label: item.props?.label,
                name: item.props?.name,
                type: item.props?.type,
                id: item.props?.id,
            }
        })
    }, [children])

    return (
        <div ref={divRef} className={`w-[100%] p-[20px] min-h-[100px] ${canDrop ? 'border-[2px] border-[blue]' : 'border-[1px] border=[#000]'}`} data-component-id={id}>
            <AntdForm labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={form} onFinish={(values) => {
                onFinish && onFinish(values)
            }}>
                {
                    formItems.map((item: any) => {
                        return <AntdForm.Item key={item.id} data-component-id={item.id} name={item.name} label={item.label}>
                            {/* 编辑时输入框不需要输入（不响应任何鼠标事件） */}
                            <Input style={{ pointerEvents: 'none' }} />
                        </AntdForm.Item>
                    })
                }
            </AntdForm>
        </div>
    )
}